// SSE 工具类
export class SSEClient {
  constructor() {
    this.eventSource = null
    this.isCompleted = false // 添加完成标志
    this.hasReceivedData = false // 添加数据接收标志
  }

  // 连接恋爱大师应用的SSE
  connectLoveApp(message, chatId, onMessage, onError, onComplete) {
    const url = `/api/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
    
    this.isCompleted = false // 重置完成标志
    this.hasReceivedData = false // 重置数据接收标志
    this.eventSource = new EventSource(url)
    
    this.eventSource.onmessage = (event) => {
      try {
        const data = event.data
        this.hasReceivedData = true // 标记已接收到数据
        
        if (data === '[DONE]') {
          this.isCompleted = true // 标记为正常完成
          onComplete && onComplete()
          this.close()
        } else {
          onMessage && onMessage(data)
        }
      } catch (error) {
        console.error('SSE消息解析错误:', error)
        onError && onError(error)
      }
    }
    
    this.eventSource.onerror = (error) => {
      console.error('SSE连接错误 - readyState:', this.eventSource?.readyState, error)
      
      // 如果已经接收到数据，给一个短暂延时来判断是否为正常结束
      if (this.hasReceivedData && !this.isCompleted) {
        setTimeout(() => {
          if (!this.isCompleted) {
            console.log('SSE流正常结束（延时确认）')
            this.isCompleted = true
            onComplete && onComplete()
          }
          this.close()
        }, 100) // 100ms延时判断
      } else if (!this.isCompleted) {
        // 没有接收到数据就出错，直接当作连接失败处理
        console.log('SSE连接失败')
        onError && onError(error)
        this.close()
      } else {
        this.close()
      }
    }
    
    this.eventSource.onopen = () => {
      console.log('SSE连接已建立')
    }
  }

  // 连接超级智能体应用的SSE
  connectManusApp(message, onMessage, onError, onComplete) {
    const url = `/api/ai/manus/chat?message=${encodeURIComponent(message)}`
    
    this.isCompleted = false // 重置完成标志
    this.hasReceivedData = false // 重置数据接收标志
    this.eventSource = new EventSource(url)
    
    this.eventSource.onmessage = (event) => {
      try {
        const data = event.data
        this.hasReceivedData = true // 标记已接收到数据
        
        if (data === '[DONE]') {
          this.isCompleted = true // 标记为正常完成
          onComplete && onComplete()
          this.close()
        } else {
          onMessage && onMessage(data)
        }
      } catch (error) {
        console.error('SSE消息解析错误:', error)
        onError && onError(error)
      }
    }
    
    this.eventSource.onerror = (error) => {
      console.error('SSE连接错误 - readyState:', this.eventSource?.readyState, error)
      
      // 如果已经接收到数据，给一个短暂延时来判断是否为正常结束
      if (this.hasReceivedData && !this.isCompleted) {
        setTimeout(() => {
          if (!this.isCompleted) {
            console.log('SSE流正常结束（延时确认）')
            this.isCompleted = true
            onComplete && onComplete()
          }
          this.close()
        }, 100) // 100ms延时判断
      } else if (!this.isCompleted) {
        // 没有接收到数据就出错，直接当作连接失败处理
        console.log('SSE连接失败')
        onError && onError(error)
        this.close()
      } else {
        this.close()
      }
    }
    
    this.eventSource.onopen = () => {
      console.log('SSE连接已建立')
    }
  }

  // 关闭连接
  close() {
    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
      console.log('SSE连接已关闭')
    }
  }
}

// 生成聊天室ID
export function generateChatId() {
  return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}